package top.revery.task.controller;


import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import top.revery.api.util.IdUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.web.bind.annotation.RestController;
import top.revery.api.api.user.IUserInfoApi;
import top.revery.api.config.UserPageData;
import top.revery.api.entity.user.BaseCompanyUser;
import top.revery.api.entity.user.BaseUserInfo;
import top.revery.api.entity.user.BaseUserKol;
import top.revery.api.entity.vo.BaseUserInfoVo;

import top.revery.api.util.MdUtils;
import top.revery.api.util.SendMessage;
import top.revery.task.dto.CompanyDto;
import top.revery.task.dto.KolDto;

import top.revery.task.dto.UserInfoDto;
import top.revery.task.service.UserSerivce;




import java.sql.Timestamp;
import java.util.Date;
import java.util.Optional;


/**
 * @author denghao
 * @title
 * @package 用户
 * @date 2019/12/12 15:42
 */
@RestController
@Slf4j
public class UserInfoController implements IUserInfoApi {
    @Autowired
    private UserSerivce userSerivce;
    @Autowired
    private UserInfoDto userInfoDto;
    @Autowired
    private KolDto kolDto;
    @Autowired
    private CompanyDto companyDto;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public BaseUserInfo save(BaseUserInfo baseuserInfo) {

        try {
            return userInfoDto.save(baseuserInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //根据id获取用户所有信息
    @Override
    public BaseUserInfoVo findById(Long id) throws Exception{
        BaseUserInfo baseUserInfo = userInfoDto.findById(id).get();
        BaseUserInfoVo baseUserInfoVo = new BaseUserInfoVo();
        if(baseUserInfo.getUserType()==0){
            Optional<BaseUserKol> byId = kolDto.findById(id);
            if(byId.isPresent()){
                BaseUserKol baseUserKol = byId.get();
                baseUserInfoVo.setBaseUserKol(baseUserKol);
                baseUserInfoVo.setBaseUserInfo(baseUserInfo);
                return baseUserInfoVo;
            }else {
                throw new Exception("系统错误");
            }
        }
            Optional<BaseCompanyUser> byId = companyDto.findById(id);
            if (byId.isPresent()) {
                BaseCompanyUser baseCompanyUser = byId.get();
                baseUserInfoVo.setBaseCompanyUser(baseCompanyUser);
                baseUserInfoVo.setBaseUserInfo(baseUserInfo);
            }
        return baseUserInfoVo;

    }

    @Override
    public UserPageData getList(int pageNum, int pageSize) {
        try {
            Page<BaseUserInfo> pageList = userSerivce.findPage(pageNum, pageSize);
            UserPageData userPageData = new UserPageData();
            userPageData.list = pageList.getContent();
            userPageData.rows = pageList.getTotalElements();
            System.out.println(userPageData);
            return userPageData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取手机号验证码
    @Override
    public String sendsms(String mobile) throws Exception {
        //  判断是否填写手机号码
        if (mobile == null) {
            //  未填写手机号码，返回失败提示
            throw new Exception("请输入手机号码");

        }
        //  判断用户填写的手机号码是否合法
        if (!mobile.matches("^1[^124]\\d{9}$")) {
            //  手机号码不合法，返回失败提示
            throw new Exception("手机号码不合法，请重新输入!");

        }
        BaseUserInfo user = userInfoDto.findByTelephone(mobile);
        if (user != null) {
            throw new Exception("用户已注册!请登录");
        }

        //redisTemplate.opsForValue().set(mobile, "123456");
        //  redisTemplate.expire(mobile, 300, TimeUnit.SECONDS);
        SendMessage sendMessage = new SendMessage();
        //发送短信，发回加密的验证密钥
        String codeSign = sendMessage.send(mobile, "2马路", SendMessage.SMS_TemplateI.VERIFICATION_CODE);
        // System.out.println(codeSign);
        return codeSign;

    }

    @GlobalTransactional
    @Override
    public BaseUserInfo register(String code, String codeSign, String name, String telephone, int userType, String password, String email) throws Exception {

     /*   if (email == null || !email.matches("^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$")) {
            throw new Exception("邮箱格式不对或没有填写！");
    }*/
        BaseUserInfo userInfo = userSerivce.findByTelephone(telephone);
        BaseUserInfo uname = userSerivce.findByName(name);
        //  BaseUserInfo uemail = userSerivce.findByEmail(email);
        if (userInfo != null || uname != null) {
            throw new Exception("用户已注册,请直接登录!");
        }
        if (password == null) {
            throw new Exception("密码还未填写，请输入密码！");
        }
        SendMessage sendMessage = new SendMessage();
        boolean b = sendMessage.checkCodeSign(code, telephone, codeSign);
        if (b == false) {
            throw new Exception("验证码错误或过期,请重新输入!");
        }
       /* String redisCode = redisTemplate.opsForValue().get(telephone);
        if (redisCode == null || redisCode.equals("") || !code.equals(redisCode)) {
            throw new Exception("验证码已过期或者输入错误！");
        }*/
        if (userType == 0) {
            //创建用户对象
            BaseUserInfo user = new BaseUserInfo();
            user.setName(name);
            user.setEmail(email);
            user.setTelephone(telephone);
            user.setPassword(MdUtils.getMD5Str(password));
            user.setUserType(0);
            user.setAddTime(new Timestamp(new Date().getTime()));
            userInfoDto.save(user);

            //创建网红
            BaseUserKol userKol = new BaseUserKol();
            userKol.setId(user.getId());

            userKol.setKolID(IdUtil.getUUID());
            userKol.setEmail(email);
            userKol.setTelephone(telephone);
            kolDto.save(userKol);

            return user;
        } else {
            //创建用户对象
            BaseUserInfo user = new BaseUserInfo();
            user.setName(name);
            user.setEmail(email);
            user.setTelephone(telephone);
            user.setPassword(MdUtils.getMD5Str(password));
            user.setUserType(1);
            user.setAddTime(new Timestamp(new Date().getTime()));
            userInfoDto.save(user);
            //创建企业
            BaseCompanyUser companyUser = new BaseCompanyUser();
            companyUser.setId(user.getId());
            companyUser.setEmail(email);
            companyUser.setTelephone(telephone);
            companyDto.save(companyUser);
            return user;
        }
    }

    @Override
    public BaseUserInfo login(String name, String password) throws Exception {

        if (name == null || password == null) {
            throw new Exception("输入的不能为空！请输入相应的用户名或邮箱或手机号及密码！");
        }
        if (name.matches("^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$")) {
            BaseUserInfo userInfo = userSerivce.findByEmail(name);
            if (userInfo == null) {
                throw new Exception("您还没有注册，请注册之后登录！");
            }
            if (!MdUtils.getMD5Str(password).equals(userInfo.getPassword())) {
                throw new Exception("密码错误！");
            }
            return userInfo;
        }
        if (name.matches("^1[^124]\\d{9}$")) {
            BaseUserInfo userInfo = userSerivce.findByTelephone(name);
            if (userInfo == null) {
                throw new Exception("您还没有注册，请注册之后登录！");
            }
            if (!MdUtils.getMD5Str(password).equals(userInfo.getPassword())) {
                throw new Exception("密码错误！");
            }
            return userInfo;
        }
        BaseUserInfo userInfo = userSerivce.findByName(name);
        if (userInfo == null) {
            throw new Exception("您还没有注册，请注册之后登录！");
        }

        if (!MdUtils.getMD5Str(password).equals(userInfo.getPassword())) {
            throw new Exception("密码错误！");
        }
        return userInfo;
    }

    //忘记密码
    @Override
    public Boolean forget(String code, String codeSign, String telephone, String password) throws Exception {
//        String redisCode = redisTemplate.opsForValue().get(telephone);
//        if (redisCode == null || redisCode.equals("") || !code.equals(redisCode)) {
//            throw new Exception("验证码已过期或者输入错误！");
//        }

        SendMessage sendMessage = new SendMessage();
        boolean b = sendMessage.checkCodeSign(code, telephone, codeSign);
        if (b == false) {
            throw new Exception("验证码错误或过期,请重新输入!");
        }
        BaseUserInfo userTel = userInfoDto.findByTelephone(telephone);
        if (userTel == null) {
            throw new Exception("用户不存在！");
        }
        userTel.setPassword(MdUtils.getMD5Str(password));
        userInfoDto.save(userTel);
        return true;
    }

   /* //退出
    @RequestMapping(value = "/logout", method = {RequestMethod.GET, RequestMethod.POST})
    public String logout(HttpSession session) {
        session.removeAttribute();
        session.invalidate();
        return "退出成功";
    }*/
}
